<template>
  <div class="payment_center_passageway">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
          justify="start"
          class="search-item-left">
          <Col class="search-item">
            <span class="search-label">支付服务商:</span>
            <Select v-model="serviceName"
              @on-change="search">
              <Option v-for="item in serviceSelectNames"
                :value="item.value"
                :key="item.value">
                {{ item.label }}
              </Option>
            </Select>
          </Col>
          <Col class="search-item">
            <span class="search-label">状态:</span>
            <Select v-model="statusType"
              @on-change="search">
              <Option v-for="item in selectStatus"
                :value="item.value"
                :key="item.value">
                {{ item.label }}
              </Option>
            </Select>
          </Col>
          <Col class="search-item">
            <Button class="search-btn"
              type="primary"
              @click="search">查询</Button>
          </Col>
          <Col class="search-item">
            <Button class="search-btn"
              @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex"
          justify="end"
          class="search-item-right">
          <Col class="search-item">
            <Button class="search-btn"
              type="primary"
              v-if="hasPermission('moms:pay:channelcreate')"
              @click="skipAdd">新增</Button>
          </Col>
        </Row>
      </Row>
    </div>
    <Table stripe
      :height="this.tableHeight"
      class="table-list"
      :loading="loading"
      :columns="columns"
      :data="data">
      <template slot-scope="{ row }"
        slot="channelType">
        <span>{{ getEnumsName(row.channelType, payPassages) }}</span>
      </template>
      <template slot-scope="{ row }"
        slot="channelCode">
        <span>{{ getEnumsName(row.channelCode, payways) }}</span>
      </template>
      <template slot-scope="{ row }"
        slot="providerType">
        <span>{{ getEnumsName(row.providerType, serviceTypeLists) }}</span>
      </template>
      <template slot-scope="{ row }"
        slot="rate">
        <span>{{ row.rate ? row.rate.toFixed(2) + '%' : '' }}</span>
      </template>
      <template slot-scope="{ row, index }"
        slot="channelStatus">
        <span>
          <i-switch v-model="row.channelStatus"
            :loading="row.isLoading"
            :disabled="!hasPermission('moms:pay:channelupdatestatus')"
            @on-change="changeSwitch(...arguments, row, index)">
            <span slot="open">开</span>
            <span slot="close">关</span>
          </i-switch>
        </span>
      </template>
      <template slot-scope="{ row, index }"
        slot="action">
        <i class="iconsys iconedit"
          title="编辑"
          v-if="hasPermission('moms:pay:channelupdate')"
          @click="skipEdit(row)"></i>
        <Poptip confirm transfer
          title="你确定要删除吗？"
          @on-ok="ok(row)"
          v-if="hasPermission('moms:pay:channeldelete')"
          style="text-align: left">
          <i class="iconsys icondel"
            title="删除"></i>
        </Poptip>
      </template>
    </Table>
    <Row type="flex">
      <Col span="12"
        class="module-menu-nav">
      </Col>
      <Col span="12">
        <div class="page-box">
          <Page :total="total"
            :page-size="pageSize"
            :current="pageIndex"
            show-total
            show-sizer
            @on-change="changePageIndex"
            @on-page-size-change="changePageSize" />
        </div>
      </Col>
    </Row>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import statusMixins from '../mixins/status'
import serviceMixins from '../mixins/serviceType'
import passageMixins from '../mixins/payPassage'
import { getPassagewayLists, deletePassageway, updatePassagewayVerify, updatePassagewayStatus } from '@/api/pay/passageway.js'
export default {
  name: 'payment_passageway_list',
  mixins: [statusMixins, serviceMixins, passageMixins],
  data () {
    return {
      tableHeight: 0,
      statusType: '-1',
      serviceName: '-1',
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      loading: true,
      data: [],
      columns: [
        {
          title: '通道编号',
          key: 'channelNo',
          minWidth: 160,
          fixed: 'left'
        },
        {
          title: '支付通道类型',
          slot: 'channelType',
          minWidth: 150,
          align: 'center'
        },
        {
          title: '支付服务商',
          key: 'providerName',
          minWidth: 100,
          align: 'center'
        },
        {
          title: '支付方式',
          slot: 'channelCode',
          minWidth: 100,
          align: 'center'
        },
        {
          title: '服务商类型',
          slot: 'providerType',
          minWidth: 100,
          align: 'center'
        },
        {
          title: '费率',
          slot: 'rate',
          minWidth: 80
        },
        {
          title: '状态',
          slot: 'channelStatus',
          minWidth: 70
        },
        {
          title: '修改时间',
          key: 'updatedAt',
          minWidth: 150
        },
        {
          title: '创建时间',
          key: 'createdAt',
          minWidth: 150
        },
        {
          title: '备注',
          key: 'remark',
          width: 220
        }
      ]
    }
  },
  mounted () {
    this.getData()
    if (this.hasPermission(['moms:pay:channelupdate', 'moms:pay:channeldelete'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        fixed: 'right',
        width: 150
      })
    }
  },
  watch: {
    '$route' (newRoute) {
      const poptips = document.querySelectorAll('body .ivu-poptip-popper.ivu-poptip-confirm.v-transfer-dom')
      poptips.forEach(poptip => {
        if (poptip.style.display !== 'none') poptip.style.display = 'none'
      })
      if (newRoute.name === 'payment_passageway_list') {
        this.search()
      }
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId
    })
  },
  methods: {
    search () {
      this.pageIndex = 1
      this.getData()
    },
    reset () {
      this.serviceName = '-1'
      this.statusType = '-1'
      this.search()
    },
    changePageIndex (page) {
      this.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageSize = size
      this.search()
    },
    getData () {
      const params = {
        providerName: this.serviceName === '-1' ? '' : this.serviceName,
        channelStatus: +this.statusType,
        merchantId: this.merchantId,
        offset: (this.pageIndex - 1) * this.pageSize,
        limit: this.pageSize,
        deleted: 0
      }
      this.loading = true
      this.tableHeight = 0
      getPassagewayLists(params).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.data = (result.data || []).map(item => {
            let obj = { ...item }
            obj.channelStatus = !obj.channelStatus
            return obj
          })
          if (this.data.length > 10) {
            this.tableHeight = 520
          }
          this.total = result.totalCount || 0
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
        this.loading = false
      })
    },
    skipAdd () {
      this.$router.push({ name: 'payment_passageway_create' })
    },
    skipEdit (row) {
      updatePassagewayVerify({
        merchantId: this.merchantId,
        paymentChannelId: row.paymentChannelId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$router.push({ name: 'payment_passageway_edit', params: { id: row.paymentChannelId } })
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    ok (row) {
      deletePassageway({
        merchantId: this.merchantId,
        paymentChannelId: row.paymentChannelId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('删除成功！')
          this.getData()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    changeSwitch (nowStatus, row, index) {
      let newRow = { ...row }
      this.$nextTick(() => {
        newRow.channelStatus = !nowStatus
        newRow.isLoading = true
        this.$set(this.data, index, newRow)
      })
      const status = row.channelStatus
      updatePassagewayStatus({
        merchantId: this.merchantId,
        paymentChannelId: row.paymentChannelId,
        channelStatus: status ? 0 : 1
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success(status ? '开启成功！' : '关闭成功！')
          this.$nextTick(() => {
            newRow.channelStatus = nowStatus
            newRow.isLoading = false
            this.$set(this.data, index, newRow)
          })
        } else {
          this.$nextTick(() => {
            newRow.channelStatus = !nowStatus
            newRow.isLoading = false
            this.$set(this.data, index, newRow)
          })
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$nextTick(() => {
          newRow.channelStatus = !nowStatus
          newRow.isLoading = false
          this.$set(this.data, index, newRow)
        })
        this.$Message.error(`${err}`)
      })
    },
    getEnumsName (value, enums) {
      const result = enums.filter(item => item.value === value + '')
      return result[0] ? result[0].label : ''
    }
  }
}
</script>

<style lang="less">
.payment_center_passageway {
  .search-box {
    .search-item-left {
      width: 70%;
    }
    .search-item-right {
      width: 30%;
    }
  }
  .ivu-table-tip {
    span {
      position: absolute;
      width: 100px;
      left: 50%;
      margin-left: -50px;
    }
  }
}
</style>
